
const watermark = {}

/**
 *
 * @param {要设置的水印的内容} str
 * @param {需要设置水印的容器} container
 */
const setWatermark = (str, container, id, zIndex) => {
    // const id = '1.23452384164.123412415'


    if (container === undefined) {
        return
    }

    // 查看页面上有没有，如果有则删除
    if (document.getElementById(id) !== null) {
        const childelement = document.getElementById(id)
        childelement.parentNode.removeChild(childelement)
    }


    var containerWidth = container.offsetWidth // 获取父容器宽
    var containerHeight = container.offsetHeight // 获取父容器高
    container.style.position = 'relative' // 设置布局为相对布局

    // 创建canvas元素(先制作一块背景图)
    const can = document.createElement('canvas')
    can.width = 150 // 设置每一块的宽度
    can.height = 80 // 高度
    const cans = can.getContext('2d') // 获取canvas画布
    cans.rotate(-20 * Math.PI / 180) // 逆时针旋转π/9  cans.font = '20px Vedana' // 设置字体
    cans.fillStyle = 'rgba(200, 200, 200,0.6)' // 设置字体的颜色
    cans.textAlign = 'left' // 文本对齐方式
    cans.textBaseline = 'Middle' // 文本基线
    // cans.wordBreak = 'break-all'
    // : 
    function getWrapText(text = "", maxWidth = 140) {
        let txtList = [];
        let str = "";
        for (let i = 0, len = text.length; i < len; i++) {
            str += text.charAt(i);
            if (cans.measureText(str).width > maxWidth) {
                txtList.push(str.substring(0, str.length - 1))
                str = ""
                i--
            }
        }
        txtList.push(str)
        return txtList;
    }
    function drawText(text, x = 0, y = 0, lineHeight = 16, maxWidth = 140) {
        // ctx.font = window.getComputedStyle(canvas).font;
        // ctx.fillStyle = 'white'
        // ctx.textAlign = "start"
        // ctx.textBaseline = "top"
        getWrapText(text, maxWidth).forEach((txt, index) => {
            cans.fillText(txt, x, y + lineHeight * index);
        })
    }
    drawText(str, 0, 4 * can.height / 5)
    // cans.fillText(str, 0, 4 * can.height / 5) // 绘制文字

    //监听属性
    var options = {
        childList: true,
        attributes: true,
        subtree: true,
        attributesOldValue: true,
        characterData: true,
        characterDataOldValue: true,
    };

    // 创建一个div元素
    const div = document.createElement('div')
    div.id = id // 设置id
    div.style.pointerEvents = 'none' // 取消所有事件
    div.style.top = '0px'
    div.style.left = '0px'
    div.style.position = 'absolute'
    div.style.zIndex = zIndex
    div.style.width = containerWidth + 'px'
    div.style.height = containerHeight + 'px'
    div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
    container.appendChild(div) // 追加到页面
    // 当观察到变动时执行的回调函数
    const reset = (expression = () => { }) => {
        setTimeout(() => {
            observer.disconnect();
            // 执行恢复方法
            expression();
            observer.observe(div, options);
        }, 0);
    }

    const callback = (records) => {
        const record = records[0];
        if (record.type === 'attributes' && record.attributeName === 'style') {
            reset(() => {
                div.setAttribute('style', 'pointer-events: none; top: 0px; left: 0px; position: absolute; z-index: ' + zIndex + '; width: ' + containerWidth + 'px' + '; height: ' + containerHeight + 'px' + '; background: ' + 'url(' + can.toDataURL('image/png') + ') left top repeat');
                // div.setAttribute('style', 'background:#000;');
            });
        } else if (record.type === 'characterData') {
            reset(() => {
                // container.textContent = '别改我'
            });
        }
    }
    // 创建一个观察器实例并传入回调函数

    const observer = new MutationObserver(callback);


    // 以上述配置开始观察目标节点
    observer.observe(div, options);
    return id
}

// 该方法只允许调用一次
watermark.set = (str, container, ids, zIndex) => {
    let id = setWatermark(str, container, ids, zIndex)
    // setInterval(() => {
    //     if (document.getElementById(id) === null) {
    //         id = setWatermark(str, container, ids, zIndex)
    //         console.log('调用')
    //     }
    // }, 500)
    // 监听页面大小的变化
    window.onresize = () => {
        setWatermark(str, container, id, zIndex)
    }
}

export default watermark